import netWork from '@/lib/axios'
import qs from 'qs'

const axios = {
    namespaced: true,
    state: {
        version: '1.00',
        headers: {}
    },
    mutations: {
        SET_AXIOS_HEADERS(state, val) {
            state.headers['Content-Type'] = val === 'form-data' ? 'application/x-www-form-urlencoded' : 'application/json;charset=UTF-8'
            state.headers['timestamp'] = new Date().valueOf()
        }
    },
    actions: {
        async GET({ state, commit }, payload) {
            commit('SET_AXIOS_HEADERS', 'JSON')
            const rep = await netWork.axios.get(`${payload.url}?timestamp=${new Date().valueOf()}&${qs.stringify(payload.data)}`)
            return rep.data ? rep.data : rep
        },
        async POST_BODY({ state, commit }, payload) {
            commit('SET_AXIOS_HEADERS', 'json')
            const rep = await netWork.axios.post(payload.url, payload.data, { headers: state.headers })
            return rep.data ? rep.data : rep
        },
        async POST_FORM({ state, commit }, payload) {
            commit('SET_AXIOS_HEADERS', 'form-data')
            const rep = await netWork.axios.post(payload.url, qs.stringify(payload.data), { headers: state.headers })
            return rep.data ? rep.data : rep
        }
    }
}

export default axios
